package com.moon.common.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.moon.common.dao.IBaseDao;
import com.moon.common.utils.Page;
import com.moon.common.utils.hql.QueryUtils;

@SuppressWarnings("unchecked")
public class BaseService {

	private IBaseDao baseDao;

	Page findPage(Page page, Class clazz ,HttpServletRequest request,String prefix) {
		Map filterParams = QueryUtils.getParametersStartWithPrefix(request,prefix);
		String hql = QueryUtils.bulidQuery(clazz, filterParams);
		Map params = QueryUtils.bulidParams(filterParams);
		page = baseDao.findPageByHql(page.getStart(), page.getLimit(), hql, params);
		return page;
	}
	
	List findList(Class clazz, HttpServletRequest request,String prefix) {
		List list = null;
		Map filterParams = QueryUtils.getParametersStartWithPrefix(request,prefix);
		String hql = QueryUtils.bulidQuery(clazz, filterParams);
		Map params = QueryUtils.bulidParams(filterParams);
		list = baseDao.findListByHql(hql, params);
		return list;
	}
	
	Page findPage(Page page,String hql,Map params){
		page = baseDao.findPageByHql(page.getStart(), page.getLimit(), hql, params);
		return page;
	}
	
	List findList(String hql,Map params){
		List list = null;
		list = baseDao.findListByHql(hql, params);
		return list;
	}
	
	List getAllAsList(Class clazz) {
		String hql = "from "+clazz.getSimpleName()+"";
		return baseDao.findListByHql(hql,new HashMap());
	}

	Object findObjectById(Class clazz,Long id) {
		return baseDao.findObjectById(clazz, id);
	}
	
	Object findObjectByHql(String hql,Map params){
		return baseDao.findObjectByHql(hql, params);
	}
	
	void deleteByIds(Class clazz,String[] ids) {
		for(int i=0 ;i<ids.length;i++){
			Long id = Long.parseLong(ids[i]);
			deleteById(clazz, id);
		}
	}

	void deleteByIds(Class clazz,Long[] ids) {
		for(Long id:ids){
			deleteById(clazz,id);
		}
	}
	
	void deleteByStrs(Class clazz,String columnName,String[] columnValues) {
		for(String columnValue:columnValues){
			deleteByStr(clazz,columnName,columnValue);
		}
	}
	
	void deleteByStr(Class clazz,String columnName,String columnValue) {
		String hql = "delete from "+clazz.getSimpleName()+" " +
				"where "+columnName+"='"+columnValue+"'";
		baseDao.executeHql(hql);
	}

	void deleteById(Class clazz,Long id) {
		baseDao.deleteById(clazz, id);
	}
	
	void update(Object obj) {
		baseDao.update(obj);
	}

	void save(Object obj) {
		baseDao.save(obj);
	}

	void delete(Object obj) {
		baseDao.delete(obj);
	}
	
	public IBaseDao getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(IBaseDao baseDao) {
		this.baseDao = baseDao;
	}
	
}
